#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>

#include "Common.hpp"
#include "Protocol.hpp" // 形成约定

// ./client_tcp server_ip server_port
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        std::cout << "Usage:./client_tcp server_ip server_port" << std::endl;
        return 1;
    }
    const char* server_ip = argv[1];        // 服务器IP地址
    int server_port = std::stoi(argv[2]);   // 服务器端口号

    // 创建套接字
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        std::cout << "create socket failed" << std::endl;
        return 2;
    }

    // 填充网络信息
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(server_port);
    server_addr.sin_addr.s_addr = inet_addr(server_ip);

    // client 不需要显示的进行bind, tcp是面向连接的, connect 底层会自动进行bind
    // 因为都是客户端链接服务器, 所以不需要bind
    // 客户端通过connect函数发起连接请求
    int n = ::connect(sockfd, CONV(&server_addr), sizeof(server_addr));
    if(n < 0)
    {
        std::cout << "connect failed" << std::endl;
        return 3;
    }
    // echo client
    std::string message;
    while(true)
    {
        int x = 0, y = 0;
        char oper;
        std::cout << "input x: ";
        std::cin >> x;
        std::cout << "input y: ";
        std::cin >> y;
        std::cout << "input oper: ";
        std::cin >> oper;

        Request req(x, y, oper);
        // 1. 序列化
        req.Serialize(message);

        // 2. 添加报头
        Encode(message);

        // 3. 通过socket发送
        //从cin中获取消息之后，通过socket向server端发消息
        n = ::send(sockfd, message.c_str(), message.size(), 0);   
        if(n > 0)   // 写成功了
        {
            char inbuffer[1024];
            // 4.获得应答
            // 从socket里面读取server端发来的消息
            int m  = ::recv(sockfd, inbuffer,sizeof(inbuffer), 0);
            if(m > 0)
            {
                inbuffer[m] = 0;
                std::string packet = inbuffer;
                std::string content;
                // 5. 去掉报头
                Decode(packet, &content);

                // 6. 服务端反序列化
                Response resp;
                resp.Deserialize(content);

                // 7. 得到结构化的结果
                std::cout << resp.Result() << "[" << resp.Code() << "]" << std::endl;
            }
            else    break;
        }
        else    
            break;
    }

    // 关闭套接字
    ::close(sockfd);
    return 0;
}